package plat

import (
	"net/http"
	"time"

	"github.com/lauyoume/gohttp"
)

var (
	default_useragent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
	httpproxy         string
)

func SetHttpProxy(proxy string) {
	httpproxy = proxy
}

type plathttp struct {
	Host   string
	Cookie string
}

func newbaijia(ck string) *plathttp {
	return &plathttp{
		Host:   "http://baijiahao.baidu.com",
		Cookie: ck,
	}
}

func newtoutiao(ck string) *plathttp {
	return &plathttp{
		Host:   "https://mp.toutiao.com",
		Cookie: ck,
	}
}

func (p *plathttp) getReq(ul string, headers ...string) ([]byte, error) {
	req := gohttp.New()
	req.Get(ul).Timeout(60*time.Second).
		Set("User-Agent", default_useragent).
		Set("Cookie", p.Cookie).
		Set("Pragma", "no-cache").
		Set("Cache-Control", "no-cache")

	for i := 0; i < len(headers); i += 2 {
		req.Set(headers[i], headers[i+1])
	}
	req.Jar(false)
	if httpproxy != "" {
		req.Proxy(httpproxy)
	}

	body, _, err := req.Bytes(http.StatusOK)
	// body, _, err := goutils.GetBodyFromReq(req, http.StatusOK)
	if err != nil {
		return nil, err
	}

	return body, nil
}

func (p *plathttp) postReq(ul string, typ string, data interface{}, headers ...string) ([]byte, error) {
	req := gohttp.New()
	req.Post(ul).Type(typ).Timeout(60*time.Second).
		Set("User-Agent", default_useragent).
		Set("Cookie", p.Cookie).
		Set("Pragma", "no-cache").
		Set("Cache-Control", "no-cache").
		Send(data)

	for i := 0; i < len(headers); i += 2 {
		req.Set(headers[i], headers[i+1])
	}

	// body, _, err := goutils.GetBodyFromReq(req, http.StatusOK)
	body, _, err := req.Bytes(http.StatusOK)
	if err != nil {
		return nil, err
	}
	return body, nil
}

func (p *plathttp) url(v string) string {
	return p.Host + v
}

func (p *plathttp) setCookie(ck string) {
	p.Cookie = ck
}
